/**
 * 考试相关接口
 */

import request from '@/utils/request'

export default {
  /**
   * 考试前获取试卷内容
   * @param {Object} params - { course_id, paper_id }
   * @returns {Promise} 试卷题目内容
   */
  getPaperDetail(params) {
    return request({
      url: '/student/paper-detail',
      method: 'get',
      params
    })
  },

  /**
   * 提交答案并自动评分
   * @param {Object} data - { course_id, paper_id, answers }
   * @param {Array} data.answers - 答案数组，格式: [{ question_id: 1, answer: "A" }, ...]
   * @returns {Promise} 评分结果
   * 
   * 答案格式说明:
   * - 单选题: answer 为单个选项，如 "A"
   * - 多选题: answer 为逗号分隔的选项，如 "A,B,C"
   * - 判断题: answer 为 "正确" 或 "错误"
   * 
   * 注意: 后端期望 answers 为对象格式 {question_id: answer, ...}
   */
  submitPaper(data) {
    // 兼容两种格式：数组格式和对象格式
    let answersObject = {}
    
    if (Array.isArray(data.answers)) {
      // 数组格式: [{question_id: 1, answer: "A"}, ...]
      data.answers.forEach(item => {
        answersObject[item.question_id] = item.answer
      })
    } else if (typeof data.answers === 'object' && data.answers !== null) {
      // 对象格式: {question_id: answer, ...}
      answersObject = data.answers
    }
    
    return request({
      url: '/student/submit-paper',
      method: 'post',
      data: {
        course_id: data.course_id,
        paper_id: data.paper_id,
        answers: answersObject
      }
    })
  },

  /**
   * 获取已完成试卷的结果（查看成绩和错题）
   * @param {Object} params - { course_id, paper_id }
   * @returns {Promise} 试卷结果：分数、错题详情等
   */
  getPaperResult(params) {
    return request({
      url: '/student/paper-result',
      method: 'get',
      params
    })
  }
}
